package com.shiku.imserver.common.tcp;

import com.shiku.imserver.common.packets.ImPacket;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.exception.AioDecodeException;

public class TcpServerDecoder {
    private static Logger logger = LoggerFactory.getLogger(TcpServerDecoder.class);

    public static TcpPacket decode(ByteBuffer buffer, ChannelContext channelContext) throws AioDecodeException {
        TcpPacket tcpPacket = null;
        if (isHeaderLength(buffer)) {
            byte version = buffer.get();
            byte maskByte = buffer.get();
            Integer synSeq = 0;
            if (ImPacket.decodeHasSynSeq(maskByte)) {
                synSeq = Integer.valueOf(buffer.getInt());
            }
            short cmdByte = buffer.getShort();
            int bodyLen = buffer.getInt();
            if (bodyLen < 0) {
                throw new AioDecodeException("bodyLength [" + bodyLen + "] is not right, remote:" + channelContext.getClientNode());
            } else if ((buffer.limit() - buffer.position()) - bodyLen >= 0) {
                byte[] body = new byte[bodyLen];
                try {
                    buffer.get(body, 0, bodyLen);
                } catch (Exception e) {
                    logger.error(e.toString());
                }
                tcpPacket = new TcpPacket(cmdByte, body);
                tcpPacket.setVersion(version);
                tcpPacket.setMask(maskByte);
                if (synSeq.intValue() > 0) {
                    tcpPacket.setSynSeq(synSeq);
                    try {
                        channelContext.getGroupContext().getAioHandler().handler(tcpPacket, channelContext);
                    } catch (Exception e2) {
                        logger.error("同步发送解码调用handler异常!" + e2);
                    }
                }
            }
        }
        return tcpPacket;
    }

    private static boolean isHeaderLength(ByteBuffer buffer) throws AioDecodeException {
        if (buffer.limit() - buffer.position() == 0) {
            return false;
        }
        int index = buffer.position();
        try {
            buffer.get(index);
            int index2 = index + 1;
            byte maskByte = buffer.get(index2);
            int index3 = index2 + 1;
            if (ImPacket.decodeHasSynSeq(maskByte)) {
                buffer.getInt(index3);
                index3 += 4;
            }
            buffer.getShort(index3);
            int index4 = index3 + 2;
            buffer.getInt(index4);
            int index5 = index4 + 4;
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
